/*
 * Functions for dynamically updating the interface using Ajax.
 *
 * PAGINATION
 * 1. Begin with structure:
 *    <div id="container">[page_1_html]</div>
 *    <div id="containerMore">[more_link]</div>
 * 2. more_link makes Ajax request using ajax_x()
 * 3. server responds with targeted HTML for update_html(), including:
 *    a) page_2_html targeted at 'container*' (the * tells update_html() to
 *       add the content not to 'container' but as a child div of 'container',
 *       preserving any existing content).
 *    b) more_link modified to request next page, or '' if the last page has
 *       just been requested
 */

/* http://peterstuifzand.nl/2008/09/05/jquery-and-postjson.html */
$.postJSON = function (url, callback) {
    $.ajax({
        'url': url,
        'type': 'post',
        'processData': false,
        contentType: 'application/json',
        success: function (data) { 
            callback(JSON.parse(data));
        }
    });
};

$.submitJSON = function (url, data, callback) {
    $.ajax({
        'url': url,
        'type': 'post',
        'processData': false,
        'data': data,
        contentType: 'application/x-www-form-urlencoded',
        success: function (data) {
            callback(JSON.parse(data));
        }
    });
};

function ajax_post(url) {
    $.postJSON(url, update_html);
}

function ajax_submit(url, form_id) {
    $.submitJSON(url, $(form_id).serialize(), update_html);
}

function ajax_get(url) {
    $.getJSON(url, update_html);
}

/* see server-side ajax_response() */
function update_html(data) {
    $.each(data, function(index, element) {
        switch (element.method) {
            case 'prepend':
                $(element.target).prepend(element.html); break;
            case 'update':
                $(element.target).html(element.html); break;
            case 'append':
                $(element.target).append(element.html); break;
        }
    });
}

/**
 * Issue HTTP POST request from JavaScript.
 * eg ('/add', {"name": "James", "age": 27})
 * @param string URL of resource being posted to
 * @param mixed array of arguments to pass to the resource
 */
function http_post(action, params) {

    // dynamically create form construct on page, fill it with necessary
    // data, then submit it.
    var form = document.createElement("form");
    form.setAttribute("method", "post");
    form.setAttribute("action", action);

    for(var key in params) {
        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", key);
        hiddenField.setAttribute("value", params[key]);
        form.appendChild(hiddenField);
    }

    document.body.appendChild(form);
    form.submit();
}
